
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'

const debug = process.env.NODE_ENV !== 'production'

// create an axios instance
axios.defaults.retry = 4
axios.defaults.retryDelay = 1000

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // url = base url + request url
  timeout: 100000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const lang = Cookies.get('language') == null ? 'zh_CN' : Cookies.get('language') === 'cn' || Cookies.get('language') === 'zh' ? 'zh_CN' : 'en_US'
    // eslint-disable-next-line eqeqeq
    if (config.method == 'get') {
      // eslint-disable-next-line eqeqeq
      if (config.url.indexOf('?') == -1) {
        config.url = config.url + '?lang=' + lang
      } else {
        config.url = config.url + '&lang=' + lang
      }
    } else {
      config.lang = lang
    }
    if (store.getters.token) {
      config.headers['X-RD-Request-APIToken'] = getToken()
      config.headers['X-RD-Request-Language'] = lang
      console.log('config', config)
    }

    if (debug) {
      // console.log(config)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (debug) {
      // console.log(res)
    }
    if (res.code !== 'SUCCESS') {
      Message({
        message: res.msg,
        dangerouslyUseHTMLString: true,
        type: 'error',
        duration: 5000
      })
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === '401') {
        // 请自行在引入 MessageBox
        // import { Message, MessageBox } from 'element-ui'
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (res.code === '4001') {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      }

      return Promise.reject('error')
    } else {
      if (response.data && response.data.data && response.data.data.pageSize) {
        response.data.data.pagination = {
          pageNum: response.data.data.pageNum,
          pageSize: response.data.data.pageSize,
          total: response.data.data.total
        }
      }
      return response.data
    }
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 401: Message.error('账号已被禁用或账号不存在'); break
        default: Message.error('请求超时，请稍后再试!')
      }
    }
    return Promise.reject(error)
  }
)

export default service
